package com.aj.activity.fragment;

import java.io.File;
import java.text.DecimalFormat;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aj.activity.R;
import com.aj.activity.dialog.InfoDialog;
import com.aj.activity.dialog.InfoDialog.IInfoInterface;
import com.aj.activity.dialog.LogoutDialog;
import com.aj.activity.dialog.LogoutDialog.ILogoutInterface;
import com.aj.application.LoveHomeApplication;
import com.aj.utils.Contants;

/**
 * A simple {@link Fragment} subclass.
 */
public class SettingsFragment extends Fragment implements ILogoutInterface {

	private LogoutDialog dialog;

	private TextView datamanage;

	private TextView register_text;

	private TextView login_text;

	private TextView homesafe;

	private TextView clear;

	private TextView qrcodedownload;

	private LinearLayout nologin_linearlayout;

	private LinearLayout login_linearlayout;

	private TextView username_text;

	private TextView personalsignature_text;

	private LinearLayout tools_linearlayout;

	private ImageView goto_edit;

	private InfoDialog infoDialog;

	private ProgressDialog progressDialog;

	private void showProgressDialog() {
		showProgressDialog(R.string.data_loading_text);
	}

	private void showProgressDialog(String message) {
		if (progressDialog == null) {
			progressDialog = new ProgressDialog(getContext());
			progressDialog.setMessage(message);
			progressDialog.show();
		}
	}

	private void showProgressDialog(int messageId) {
		if (progressDialog == null) {
			progressDialog = new ProgressDialog(getContext());
			progressDialog.setMessage(getString(messageId));
			progressDialog.show();
		}
	}

	private void dimmissProgressDialog() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	private void showInfoDialog(String message, String okText,
			String cannelText, IInfoInterface infoInterface) {
		if (infoDialog == null) {
			infoDialog = new InfoDialog(getContext());
		}
		infoDialog.show();
		infoDialog.setContent(message);
		infoDialog.setSureButtonText(okText);
		infoDialog.setCannelButtonText(cannelText);
		infoDialog.setInfoInterface(infoInterface);
	}

	private void initVisibleView(boolean isLogin) {
		if (isLogin) {
			nologin_linearlayout.setVisibility(View.GONE);
			login_linearlayout.setVisibility(View.VISIBLE);
			goto_edit.setVisibility(View.VISIBLE);
			tools_linearlayout.setVisibility(View.VISIBLE);
		} else {
			nologin_linearlayout.setVisibility(View.VISIBLE);
			login_linearlayout.setVisibility(View.GONE);
			goto_edit.setVisibility(View.GONE);
			tools_linearlayout.setVisibility(View.GONE);
		}
	}

	public SettingsFragment() {
	}

	@Override
	public void onResume() {
		super.onResume();
		initVisibleView(LoveHomeApplication.token != null
				&& LoveHomeApplication.token.trim().length() > 0);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_settings, container,
				false);
		initView(view);
		return view;
	}

	private void initView(View view) {
		datamanage = (TextView) view.findViewById(R.id.datamanage);
		register_text = (TextView) view.findViewById(R.id.register_text);
		login_text = (TextView) view.findViewById(R.id.login_text);
		homesafe = (TextView) view.findViewById(R.id.homesafe);
		clear = (TextView) view.findViewById(R.id.clear);
		qrcodedownload = (TextView) view.findViewById(R.id.qrcodedownload);
		nologin_linearlayout = (LinearLayout) view
				.findViewById(R.id.nologin_linearlayout);
		login_linearlayout = (LinearLayout) view
				.findViewById(R.id.login_linearlayout);
		username_text = (TextView) view.findViewById(R.id.username_text);
		personalsignature_text = (TextView) view
				.findViewById(R.id.personalsignature_text);
		tools_linearlayout = (LinearLayout) view
				.findViewById(R.id.tools_linearlayout);
		goto_edit = (ImageView) view.findViewById(R.id.goto_edit);

		ClickEvent clickEvent = new ClickEvent();
		datamanage.setOnClickListener(clickEvent);
		register_text.setOnClickListener(clickEvent);
		login_text.setOnClickListener(clickEvent);
		homesafe.setOnClickListener(clickEvent);
		qrcodedownload.setOnClickListener(clickEvent);
		clear.setOnClickListener(clickEvent);
	}

	class ClickEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			Intent intent = null;
			switch (v.getId()) {
			case R.id.clear:
				showInfoDialog(getString(R.string.is_clear_file),
						getString(R.string.dialog_sure_text),
						getString(R.string.dialog_cannel_text),
						new IInfoInterface() {
							@Override
							public void sureInfo() {
								showProgressDialog("清理数据中，请稍后.......");
								new ClearTask(getContext())
										.execute(new Void[] { null });
							}
						});
				break;
			case R.id.datamanage:
				intent = new Intent(Contants.USERINFO_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.register_text:
				intent = new Intent(Contants.ENTER_PHONE_ACTION);
				intent.putExtra(Contants.PAGEFLAG_STRING,
						Contants.REGISTER_PAGEFLAG_STRING);
				startActivity(intent);
				break;
			case R.id.login_text:
				intent = new Intent(Contants.LOGINACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.homesafe:
				intent = new Intent(Contants.SAFE_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.qrcodedownload:
				intent = new Intent(Contants.QRCODE_DOWNLOAD_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			}
		}
	}

	@Override
	public void sureLogout() {
		getActivity().finish();
		System.exit(0);
	}

	class ClearTask extends AsyncTask<Void, Void, Long> {
		private Context context;

		public ClearTask(Context context) {
			this.context = context;
		}

		/**
		 * 运行在UI线程中，在调用doInBackground()之前执行
		 */
		@Override
		protected void onPreExecute() {
		}

		/**
		 * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
		 */
		@Override
		protected Long doInBackground(Void... params) {
			if (isCancelled()) {
				return null;
			}
			String cashLogFilePath = getFilePath() + "images/";
			String soundRecordFilePath = getFilePath() + "sound/";
			String photoRecordFilePath = getFilePath();
			File cashLogFile = new File(cashLogFilePath);
			File soundRecordFile = new File(soundRecordFilePath);
			File photoRecordFile = new File(photoRecordFilePath);
			Long fileSize = 0L;
			long tempFileSize = 0;
			if (photoRecordFile.exists()) {
				File[] photoFileList = photoRecordFile.listFiles();
				for (File tempFile : photoFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			if (cashLogFile.exists()) {
				File[] cashLogFileList = cashLogFile.listFiles();
				for (File tempFile : cashLogFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			if (soundRecordFile.exists()) {
				File[] soundRecordFileList = soundRecordFile.listFiles();
				for (File tempFile : soundRecordFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			return fileSize;
		}

		/**
		 * 运行在ui线程中，在doInBackground()执行完毕后执行
		 */
		@Override
		protected void onPostExecute(Long fileSize) {
			String message = "";
			if (fileSize.equals(0L)) {
				message = getString(R.string.local_nocache_text);
			} else {
				String tempMessage = "";
				if (fileSize < 1024) {
					tempMessage = fileSize + "B";
				} else if (fileSize >= 1024 && fileSize < 1024 * 1024) {
					DecimalFormat df = new DecimalFormat("#.###");
					tempMessage = df.format((fileSize / 1024f)) + "KB";
				} else {
					DecimalFormat df = new DecimalFormat("#.###");
					tempMessage = df.format(((fileSize / 1024f) / 1024f))
							+ "MB";
				}
				message = getString(R.string.local_cache_text) + tempMessage;
			}
			dimmissProgressDialog();
			showInfoDialog(message,
					fileSize.equals(0L) ? getString(R.string.know_button_text)
							: getString(R.string.tanks_button_text),
					getString(R.string.dialog_cannel_text), null);
		}

		/**
		 * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
		 */
		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	private String getFilePath() {
		String file_dir = "";
		// SD卡是否存在
		boolean isSDCardExist = Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState());
		// Environment.getExternalStorageDirectory()相当于File file=new
		// File("/sdcard")
		boolean isRootDirExist = Environment.getExternalStorageDirectory()
				.exists();
		if (isSDCardExist && isRootDirExist) {
			file_dir = Contants.APP_PATH;
		} else {
			// MyApplication.getInstance().getFilesDir()返回的路劲为/data/data/PACKAGE_NAME/files，其中的包就是我们建立的主Activity所在的包
			file_dir = LoveHomeApplication.application.getFilesDir()
					.getAbsolutePath();
		}
		return file_dir;
	}
}
